import React, { Fragment } from 'react'
import { View, StyleSheet, Text, ScrollView, Image } from 'react-native'
import Picker from 'react-native-picker'
import moment from 'moment'
import { StackActions } from 'react-navigation'
import { ScaleS, ScaleT } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import CustomBoxShadow from 'src/components/boxshadow/CustomBoxShadow'
import CustomButton from 'src/components/button/CustomButton'
import CustomInputLabel from 'src/components/button/CustomInputLabel'
import NextButton from 'src/components/button/NextButton'
import PromptModal from 'src/components/modal/PromptModal'
import { isEmptyObjectFn } from 'src/utils/JSTypeUtil'
import showPicker from 'src/utils/PickerUtil'
import { ShowLoading, DismissLoading, CommonToast } from 'src/utils/ToastUtil'
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION,
  DO_REQUEST_SAVEUSERINFO_B_ACTION
} from 'src/store/actions/userinfo'
import {
  INIT_FIRST_USERINFO_B_ACTION,
  UPDATE_FIRST_USERINFO_B_ACTION
} from './store/action'
import { getGenderChinese } from 'src/utils/ConfigUtil'
import { showModal } from 'src/utils/ModalUtil'
import GenderChoice from 'src/components/modal/GenderChoice'
import { keywordBlock } from 'src/utils/RegUtil'

const year = new Date().getFullYear()
const years = new Array(100).fill(0).map((e, i) => `${year - i}年`)

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  initState (payload) {
    dispatch(INIT_FIRST_USERINFO_B_ACTION(payload))
  },
  updateState (payload) {
    dispatch(UPDATE_FIRST_USERINFO_B_ACTION(payload))
  },
  doRequestSaveUserInfoToB (payload) {
    const promise = DO_REQUEST_SAVEUSERINFO_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

@connect(
  ({ userinfo, BFirstUserInfoStore }) => {
    return {
      userinfo,
      userinfoC: userinfo.C,
      ...BFirstUserInfoStore
    }
  },
  mapDispatchToProps
)
class BFirstUserInfo extends BasePage {
  constructor (props) {
    super(props)
    this.state = {
      header: {},
      saveVisible: false
    }
    const { initState, updateState, userinfoC } = this.props
    initState()
    if (!isEmptyObjectFn(userinfoC)) {
      const { userName, gmtBorth, gender } = userinfoC
      updateState({
        userName,
        gmtBorth: moment(gmtBorth).format('YYYY'),
        gender
      })
    }
  }

  childRender () {
    const { userName, gmtBorth, gender, postion } = this.props
    const { nextEnable, saveVisible } = this.state
    return (
      <Fragment>
        <ScrollView style={styles.container} contentContainerStyle={styles.containScrollView} alwaysBounceVertical={true}>
          <Text style={styles.messageTitleTopDesc}>基本信息</Text>
          <Text style={styles.messageTitleBottom}>
            *完善个人信息能更快的招到心仪的人才
          </Text>
          <CustomBoxShadow
            style={{
              ...styles.infoViewShadow,
              height: ScaleS(230),
              marginTop: ScaleS(34)
            }}
          >
            <CustomInputLabel
              title="姓名"
              value={userName}
              placeHolder="请输入"
              onPress={this._nameFieldClick}
            />
            <CustomInputLabel
              title="性别"
              value={getGenderChinese(gender)}
              placeHolder="请选择"
              onPress={this._genderFieldClick}
            />
            <CustomInputLabel
              title="出生年份"
              value={gmtBorth}
              placeHolder="请选择"
              last={true}
              onPress={this._birthFieldClick}
            />
          </CustomBoxShadow>
          <CustomBoxShadow
            style={{
              ...styles.infoViewShadow,
              marginTop: ScaleS(30),
              shadowRadius: ScaleS(30)
            }}
          >
            <CustomInputLabel
              title="我的职务"
              value={postion}
              placeHolder={'请输入'}
              last={true}
              onPress={this._postionClick}
            />
          </CustomBoxShadow>
        </ScrollView>
        <NextButton
          style={styles.nextButton}
          title="下一步"
          enable={!!nextEnable}
          onPress={this._nextBtnClick}
        />
        <PromptModal
          visible={saveVisible}
          onCancel={this.onSaveCancel}
          onConfirm={this.onSaveConfirm}
          onModalHide={this.onSaveModalHide}
          config={{
            titleText: '温馨提示',
            contentText: '内容尚未保存，确定放弃吗？'
          }}
        />
      </Fragment>
    )
  }

  componentDidMount () {}

  static getDerivedStateFromProps (props, state) {
    // console.log('getDerivedStateFromProps', state)
    return BFirstUserInfo.saveButtonEnable(props, state)
  }

  static saveButtonEnable (props, state, tip = false) {
    const {
      userName,
      gmtBorth,
      gender,
      postion
    } = props
    const nextEnable = [
      {
        key: userName,
        value: '姓名'
      },
      {
        key: gender,
        value: '性别'
      },
      {
        key: gmtBorth,
        value: '出生年月'
      },
      {
        key: postion,
        value: '职位'
      }
    ].every(e => {
      if (tip && !e.key) {
        CommonToast(`请完善您的${e.value}`)
      }
      return e.key
    })
    if (nextEnable !== state.nextEnable) {
      console.log('saveEnable change----->', nextEnable)
      return {
        nextEnable
      }
    }
    return null
  }

  _birthFieldClick = () => {
    const { gmtBorth } = this.props
    const pickerData = years
    const selectedValue = [`${gmtBorth || year - 18}年`]
    const pickerTitleText = '选择出生年份'
    showPicker({
      pickerData,
      selectedValue,
      pickerTitleText,
      onConfirm: ([gmtBorth]) => {
        this.props.updateState({
          gmtBorth: gmtBorth.replace(/年/, '')
        })
      }
    })
  }

  _nameFieldClick = () => {
    const saveCallback = userName => {
      this.props.updateState({
        userName
      })
    }
    const { userName: value } = this.props
    this.props.navigation.navigate('CommonInputPage', {
      title: '姓名',
      blockReg: keywordBlock.value,
      value,
      desc: '*请填写真实姓名',
      placeholder: '请输入姓名',
      maxLength: 6,
      saveCallback
    })
  }

  /**
   * 性别选择
   * @param type 0 boy ;1 girl
   */
  _genderFieldClick = () => {
    const { gender } = this.props
    const config = {
      gender,
      onConfirm: this.genderConfirm
    }
    this.genderModal = showModal(<GenderChoice {...config}/>)
  }

  genderConfirm = (gender) => {
    this.genderModal && this.genderModal.close()
    this.props.updateState({
      gender
    })
  }

  /**
   * 我的职务
   * @private
   */
  _postionClick = () => {
    const saveCallback = postion => {
      this.props.updateState({
        postion
      })
    }
    const { postion: value } = this.props
    this.props.navigation.navigate('CommonInputPage', {
      title: '我的职务',
      value,
      desc: '*公司组织架构的岗位名称',
      placeholder: '请输入职位名称',
      maxLength: 8,
      saveCallback
    })
  }

  /**
   * 下一步
   */
  _nextBtnClick = () => {
    const { nextEnable } = this.state
    if (!nextEnable) {
      BFirstUserInfo.saveButtonEnable(this.props, this.state, true)
      return
    }
    const {
      userName,
      gmtBorth,
      gender,
      postion,
      userinfo: {
        userId,
        mobile,
        B: { id }
      },
      doRequestSaveUserInfoToB
    } = this.props
    const params = {
      userName,
      gmtBorth: `${gmtBorth}-01-01 00:00:00`,
      gender,
      postion,
      userId,
      id,
      mobile
    }
    ShowLoading()
    doRequestSaveUserInfoToB({ params })
      .then(res => {
        console.log('doRequestSaveUserInfoToB', res)
        this.props.navigation.replace('BUserAvator', { firstLogin: true })
      })
      .finally(() => {
        DismissLoading()
      })
  }

  goBack = () => {
    const { userName, gmtBorth, gender, postion } = this.props
    if (userName || gmtBorth || gender || postion) {
      this.toggleMask(true)
      return
    }
    this.props.navigation.goBack()
  }

  toggleMask = saveVisible => {
    this.setState({
      saveVisible
    })
  }

  onSaveConfirm = () => {
    this.onSaveCancel()
  }

  onSaveCancel = () => {
    this.toggleMask(false)
  }

  onSaveModalHide = ensure => {
    ensure && this.props.navigation.goBack()
  }
}

export default BFirstUserInfo

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff'
  },
  containScrollView: {
    paddingBottom: ScaleS(90)
  },
  maskView: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    backgroundColor: '#00000055',
    zIndex: 101
  },
  messageTitleTopDesc: {
    marginHorizontal: ScaleS(20),
    marginTop: ScaleS(10),
    fontSize: ScaleT(27),
    lineHeight: ScaleS(47),
    fontWeight: 'bold',
    color: '#444444'
  },
  messageTitleBottom: {
    marginHorizontal: ScaleS(20),
    fontSize: ScaleT(12),
    lineHeight: ScaleS(28),
    color: '#FFC200'
  },

  infoViewShadow: {
    width: ScaleS(335),
    shadowColor: '#9C9C9C',
    shadowRadius: ScaleS(40),
    shadowOpacity: 0.25,
    shadowOffset: {
      width: 0,
      height: ScaleS(7)
    },
    backgroundColor: 'white',
    borderRadius: ScaleS(10),
    marginHorizontal: ScaleS(20),
    paddingHorizontal: ScaleS(16)
  },
  genderView: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  genderItemView: {},
  genderItemSelected: {
    backgroundColor: '#000000'
  },
  genderItemDefault: {
    backgroundColor: '#F0F0F0'
  },
  genderItem: {
    width: ScaleS(27),
    height: ScaleS(31)
  },
  genderVerticalLine: {
    marginHorizontal: ScaleS(20),
    width: ScaleS(1),
    height: ScaleS(16),
    backgroundColor: '#D2D2D2'
  },
  nextButton: {
    position: 'absolute',
    bottom: ScaleS(20),
    left: ScaleS(32)
  }
})
